package com.chivan.encoder;

import com.chivan.encoder.log.Logcat;

/**
 * @author Chivan
 * @description:
 * @date : 2019-12-11 14:46
 */
public class Mp3Encoder {
    static {
        System.loadLibrary("mp3encoder");
    }

    private static boolean isOpened = false;

    public byte[] encodeAudioData(byte[] audioData, int dataLength) {
        synchronized (Mp3Encoder.class) {
            if (isOpened) {
                byte[] decodeData = encode(audioData, dataLength);
                Logcat.i("Mp3压缩之前的数据长度：" + audioData.length + ",dataLength=" + dataLength);
                byte[] temp = new byte[decodeData.length];
                System.arraycopy(decodeData, 0, temp, 0, decodeData.length);
                Logcat.i("Mp3压缩之后的数据长度：" + decodeData.length);
                return temp;
            } else {
                return null;
            }
        }
    }

    public void initMp3Encoder(int audioChannels,
                               int bitRate,
                               int sampleRate,
                               int quality) {
        synchronized (Mp3Encoder.class) {
            Logcat.i("初始化mp3编码器");
            if (isOpened) {
                destroyMp3Encoder();
            }
            init(audioChannels, bitRate, sampleRate, quality);
            isOpened = true;
        }
    }

    public void destroyMp3Encoder() {
        synchronized (Mp3Encoder.class) {
            Logcat.i("销毁mp3编码器");
            destroy();
            isOpened = false;
        }
    }

    public native int init(int audioChannels,
                           int bitRate,
                           int sampleRate,
                           int quality);

    public native byte[] encode(
            byte[] buffer,
            long size
    );

    public native int destroy();
}
